package me.youline.dataServer.dao.socialActionMsg;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.transaction.Transactional;

import me.youline.dataServer.entity.socialActionMsg.SocialActionMsgNotifyRecord;
import me.youline.dataServer.entity.socialActionMsg.SocialActionMsgNotifyRecord.NotifyMsgType;
import me.youline.dataServer.utils.IdPageSqlHelper;
import me.youline.dataServer.utils.IdPagination;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Component;

/**
 * 社交事件消息通知记录DAO
 * 
 * @author linhan
 *
 */
@Component
public class SocialActionMsgNotifyRecordDAO {

	private static final String TABLE_NAME = "yline_social_notice_records";

	@Autowired
	private JdbcTemplate template;

	private static final String QUERY_SQL = " select * from " + TABLE_NAME
			+ " where %s and userId = ? order by id desc %s ";

	private static final String DELETE_BY_MSGID_SQL = "delete from "
			+ TABLE_NAME + " where msgId = ? and msgType = ?";

	private SimpleJdbcInsert insert;

	private static final RowMapper<SocialActionMsgNotifyRecord> ROW_MAPPER = new RowMapper<SocialActionMsgNotifyRecord>() {

		@Override
		public SocialActionMsgNotifyRecord mapRow(ResultSet rs, int rowNum)
				throws SQLException {
			SocialActionMsgNotifyRecord r = new SocialActionMsgNotifyRecord();
			r.setId(rs.getLong("id"));
			r.setMsgId(rs.getLong("msgId"));
			r.setUserId(rs.getLong("userId"));
			r.setMsgType(NotifyMsgType.values()[rs.getInt("msgType")]);
			r.setNotifyTime(rs.getTimestamp("notifyTime"));
			return r;
		}
	};

	@PostConstruct
	private void init() {
		insert = new SimpleJdbcInsert(template).withTableName(TABLE_NAME)
				.usingGeneratedKeyColumns("id"
						).usingColumns("userId", "msgId","msgType","notifyTime");
	}

	/**
	 * 添加社交事件消息通知记录
	 * 
	 * @param r
	 * @return
	 */
	@Transactional
	public Long addSocialActionMsgNotifyRecord(SocialActionMsgNotifyRecord r) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", r.getUserId());
		map.put("msgId", r.getMsgId());
		map.put("msgType", r.getMsgType().ordinal());
		map.put("notifyTime", r.getNotifyTime());
		return insert.executeAndReturnKey(map).longValue();
	}

	/**
	 * 分页获取社交事件消息通知记录
	 * 
	 * @param userId
	 * @param pagination
	 * @return
	 */
	public List<SocialActionMsgNotifyRecord> getSocialActionMsgNotifyRecords(
			Long userId, IdPagination pagination) {
		IdPageSqlHelper helper = IdPageSqlHelper.create(pagination, "id");
		String sql = String.format(QUERY_SQL, helper.getPagingSqlCondition(),
				helper.getSizeSqlCondition());
		Object[] data = null;
		if (helper.getIds().length == 0) {
			data = new Object[] { userId };
		} else if (helper.getIds().length == 1) {
			data = new Object[] { helper.getIds()[0], userId };
		} else if (helper.getIds().length == 2) {
			data = new Object[] { helper.getIds()[0], helper.getIds()[1],
					userId };
		}
		return template.query(sql, data, ROW_MAPPER);
	}

	/**
	 * 根据通知消息ID与通知消息类型删除通知记录
	 * 
	 * @param msgId
	 *            通知消息ID
	 * @param msgType
	 *            通知消息类型
	 * @return
	 */
	public int deleteNoticeRecord(Long msgId, NotifyMsgType msgType) {
		return template.update(DELETE_BY_MSGID_SQL, new Object[] { msgId,
				msgType });
	}

	public int deleteNoticeRecord(List<Long> msgIds, NotifyMsgType msgType) {
		List<Object[]> args = new ArrayList<Object[]>();
		for (Long id : msgIds) {
			args.add(new Object[] { id, msgType.ordinal() });
		}
		int[] r = template.batchUpdate(DELETE_BY_MSGID_SQL, args);
		if(r != null){
			int res= 0;
			for(int i : r ){
				res += i;
			}
			return res;
		}
		return 0;
	}

}
